package com.example.springboot.service;

import com.example.springboot.Mapper.UserMapper;
import com.example.springboot.exception.BusinessException;
import com.example.springboot.exception.BusinessExceptionCode;
import com.example.springboot.pojo.User;
import com.example.springboot.pojo.UserExample;
import com.example.springboot.request.UserLoginRequest;
import com.example.springboot.request.UserQueryRequest;
import com.example.springboot.request.UserResetRequest;
import com.example.springboot.request.UserSaveRequest;
import com.example.springboot.response.UserLoginResponse;
import com.example.springboot.response.UserQueryResponse;
import com.example.springboot.response.PageResponse;
import com.example.springboot.util.CopyUtil;
import com.example.springboot.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ServiceUser {

    private static final Logger LOG= LoggerFactory.getLogger(ServiceUser.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResponse<UserQueryResponse> list(UserQueryRequest userQueryRequest){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();


        if(!ObjectUtils.isEmpty(userQueryRequest.getLoginName())){
            criteria= criteria.andLoginNameEqualTo("%"+ userQueryRequest.getLoginName()+"%");
        }
        PageHelper.startPage(userQueryRequest.getPage(), userQueryRequest.getSize());
        List<User> userList=userMapper.selectByExample(userExample);


        PageInfo<User> pageInfo = new PageInfo<>(userList);
        LOG.info("总行数："+pageInfo.getTotal());
        LOG.info("总页数：" + +pageInfo.getPages());



        /*List<UserResponse> responseList=new ArrayList<>();
        for( User user:userList){
            *//*UserResponse userResponse=new UserResponse();
            BeanUtils.copyProperties(user,userResponse);*//*

            //使用CopyUtil代替上面的那两句
        UserResponse userResponse = CopyUtil.copy(user,UserResponse.class);


            responseList.add(userResponse);

        }*/


        //列表复制
        List<UserQueryResponse> list= CopyUtil.copyList(userList, UserQueryResponse.class);

        PageResponse<UserQueryResponse> pageResponse = new PageResponse<>();
        pageResponse.setTotal(pageInfo.getTotal());
        pageResponse.setList(list);
        return pageResponse;
    }

    /*
    * 保存
    * */
    public void save(UserSaveRequest request){
        User user=CopyUtil.copy(request,User.class);
        if(ObjectUtils.isEmpty(request.getId())){
            User userDB = selectByLoginName(request.getLoginName());
            if(ObjectUtils.isEmpty(userDB))
            {
                //新增
                user.setId(snowFlake.nextId());
                userMapper.insertSelective(user);
            }else{
                //用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        }
        else{
            //更新
            //先把LoginName设成空
            //而Selective方法是要检验非空的，这样就可以保证user的LoginName不能被改变。而其他的可以改变。
            user.setLoginName(null);
            user.setPassword(null);
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    /*
    * 删除
    * */
    public void delete(Long id){
        userMapper.deleteByPrimaryKey(id);

    }

    public User selectByLoginName(String LoginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andLoginNameEqualTo(LoginName);
        List<User> userList=userMapper.selectByExample(userExample);
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }else{
            return userList.get(0);
        }
    }

    /*
    * 修改密码
    * */
    public void resetPassword(UserResetRequest request){
        User user=CopyUtil.copy(request,User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }


    /*
     * 登录
     * */
    public UserLoginResponse login(UserLoginRequest request){
        //我们应该按照用户名去数据库中查找对应字段，所以可以用上面的selectByLoginName方法
        User userDB = selectByLoginName(request.getLoginName());
        if(ObjectUtils.isEmpty(userDB)){
            //如果是空 则用户名不存在
            //这里打日志是为了方便我们后台进行维护，可以在控制台看到他登录失败的原因
            LOG.info("用户名不存在,{}",request.getLoginName());

            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }else{
            //那就是用户名正确，接下来验证密码是否正确
            //如果查出来对应用户名的这条数据的密码和请求里面的密码值相同，就说明用户名密码均正确，可以登录
            if(userDB.getPassword().equals(request.getPassword())){
                //登陆成功
                //则把登录查出来的userDB复制给一个响应变量，最后返回给前端,CopyUtil.copy的左操作数是要复制的内容，右操作数是要复制进的变量的类型。
                UserLoginResponse userLoginResponse = CopyUtil.copy(userDB,UserLoginResponse.class);
                return userLoginResponse;
           }else{
                //登陆失败，密码不正确
                //同样的，我们也需要在密码不正确的时候也提供提示。
                LOG.info("密码不对，输入密码：{},数据库密码：{}",request.getPassword(),userDB.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }

    }
}
